
import time
import random
import urllib
import os.path
import numpy as np
from PIL import Image
import globalmaptiles

# construct url of imgs
# from google image
'''
google map:
url sample:
    https://khms0.google.com.hk/kh/v=138&src=app&x=810&y=421&z=10&s=Gal
    https://khms0.google.com.hk/kh/v=138&src=app&x=1614&y=839&z=11&s=G
    https://khms1.google.com/kh/v=138&src=app&x=47253&y=102811&z=18&s=Ga
    v:
    src:
    x: tile x value
    y: tile y value
    z: zoomlevel
    s: Gal means what???
    
'''
# chengdu
#upleft = (30.71,103.93)# up left coord lon,lat
#downright = (30.57,104.37)
# 
upleft = (28.9887,102.7357)# up left coord lon,lat
downright = (28.9638,102.7743)
zoomlevel = 16
tz = zoomlevel
urls = []

mercator = globalmaptiles.GlobalMercator()
mx, my = mercator.LatLonToMeters( upleft[0], upleft[1] )
tminx, tminy = mercator.MetersToTile( mx, my, tz )
gminx, gminy = mercator.GoogleTile( tminx, tminy , tz )
mx, my = mercator.LatLonToMeters( downright[0], downright[1] )
tmaxx, tmaxy = mercator.MetersToTile( mx, my, tz )
gmaxx, gmaxy = mercator.GoogleTile( tmaxx, tmaxy ,tz )

# image size
img_size = ( (gmaxx - gminx + 1) * 256, (gmaxy - gminy + 1 ) * 256 )
large_img = Image.new('RGB', img_size)

#block_size = ( 5, 5 )
#img_block = Image.new('RGB', block_size)

idx_y = 0
for gy in range(gminy, gmaxy+1):
    idx_x = 0
    for gx in range(gminx, gmaxx+1):
        if os.path.exists('%s_%s.png'%( idx_y, idx_x  )):
            print '%s_%s.png'%( idx_y, idx_x  ) + 'exist'
        else:
            tilefilename = "%s/%s/%s" % (tz, gx, gy)
            print tilefilename, "( TileMapService: z / x / y )"
            #imgfile = cStringIO.StringIO( urllib.urlopen(url).read() )
            trycount = 0
            while True:
                trycount = trycount + 1
                if trycount > 50:
                    print '\tTime out'
                    break                
                try:

                    server_id = random.randint( 0, 2 )
                    url = 'https://khms%s.google.com.hk/kh/v=138&src=app&x=%s&y=%s&z=%s&s=G'%(server_id,gx,gy,tz)
                    urllib.urlretrieve( url, '%s_%s.png'%( idx_y, idx_x  ))
                    break
                except:
                    print '\terror, try again'
        
            #img = Image.open( 'temp.png' ) 
            #large_img.paste( img, ( idx_x * 256, idx_y * 256 ))
            urls.append(url)
            print "\tGoogle:", gx, gy
            # sleep for a moment 0.1s waiting the google
            time.sleep(.1)
            #wait = input()
        
        idx_x = idx_x + 1
    idx_y = idx_y + 1
idx_y = 0
for gy in range(gminy, gmaxy+1):
    idx_x = 0
    for gx in range(gminx, gmaxx+1):
        img = Image.open( '%s_%s.png'%( idx_y, idx_x  )  ) 
        large_img.paste( img, ( idx_x * 256, idx_y * 256 ))
        idx_x = idx_x + 1
    idx_y = idx_y + 1
    
large_img.save( 'full.png' )
'''
cout = 0
for url in urls:
    cout = cout + 1
    urllib.urlretrieve( url, str(cout) + '.png')
'''
